<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>1_引出生命周期</title>
</head>
<body>
  <div id="test"></div>
  
  <script src="../js/react.development.js"></script>
  <script src="../js/react-dom.development.js"></script>
  <!-- Don't use this in production: -->
  <script src="../js/babel.min.js"></script>
  <!-- 引入prop-types.js  用于对组件标签属性进行限制 -->

  <script type="text/babel">
    // 创建组件
    // 生命周期回调函数 <=> 生命周期钩子函数 <=> 生命周期函数 <=> 生命周期钩子
    class Life extends React.Component {
      state = {
        opacity: 1
      }

      death = () => {
        // 清除定时器
        clearInterval(this.timer)
        // 卸载组件
        ReactDOM.unmountComponentAtNode(document.getElementById("test"))
      }

      /* action = () => {
        console.log('@')
        
        setInterval(() => {
          // 获取原状态
          let { opacity } = this.state;
          // 减少0.1
          opacity -= 0.1;

          if(opacity <= 0) {
            opacity = 1
          }
          // 设置新的透明度
          this.setState({
            opacity
          })
        }, 200)
      } */

      // 组件挂载完毕
      componentDidMount() {
        console.log('@')
        this.timer = setInterval(() => {
          // 获取原状态
          let { opacity } = this.state;
          // 减少0.1
          opacity -= 0.1;

          if(opacity <= 0) {
            opacity = 1
          }
          // 设置新的透明度
          this.setState({
            opacity
          })
        }, 200)
      }

      // 组件将要卸载
      componentWillUnmount() {
        // 清除定时器
        clearInterval(this.timer)
      }

      // 初始化渲染，状态更新之后
      render(h) {
        console.log('render')
        return (
          <div>
            <h2 style={{opacity: this.state.opacity}}>React学不会怎么办？</h2>
            <button onClick={this.death}>不活了</button>
            {/*<button onClick={this.action}>开始变化</button>*/}
          </div>
        )
      }
    }

    // 渲染组件
    ReactDOM.render(<Life/>, document.getElementById("test"))
  </script>
</body>
</html>